package com.home.qh.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.home.qh.dao.ClauseDao;
import com.home.qh.model.Clause;


/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve Role objects.
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> 
 */
@Repository
public class ClauseDaoHibernate extends GenericDaoHibernate<Clause, Long> implements ClauseDao {

    /**
     * Constructor to create a Generics-based version using Role as the entity
     */
    public ClauseDaoHibernate() {
        super(Clause.class);
    }

    /**
     * {@inheritDoc}
     */
    public List<Clause> getClauseByCodeAndName(String clauseCode, String clauseName) {
    	List<Clause> clauses = getHibernateTemplate().find("from Clause where name like '%?%'", clauseName);
        if (clauses.isEmpty()) {
            return null;
        } else {
            return clauses;
        }
    }

	public List<Clause> getClauseByClause(Clause clause, String sort, boolean desc, int startResult, int maxResults) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Clause.class);

        if (clause.getCode() != null) {
        	criteria.add(Restrictions.or(Restrictions.eq("code", clause.getCode()), Restrictions.eq("name", clause.getName())));
		}

        if(sort != null && !"".equalsIgnoreCase(sort)) {
            if(desc) criteria.addOrder(Order.desc(sort));
            else criteria.addOrder(Order.asc(sort));
        }

        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        
        return getHibernateTemplate().findByCriteria(criteria, startResult, maxResults);
	}

   
}
